package com.usian.user.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.usian.model.article.pojos.ApAuthor;
import com.usian.model.common.dtos.PageResponseResult;
import com.usian.model.common.dtos.ResponseResult;
import com.usian.model.common.enums.AppHttpCodeEnum;
import com.usian.model.media.pojos.WmUser;
import com.usian.model.user.dtos.AuthDto;
import com.usian.model.user.pojos.ApUser;
import com.usian.model.user.pojos.ApUserRealname;
import com.usian.user.feign.ApAuthorFeign;
import com.usian.user.feign.WmUserFeign;
import com.usian.user.mapper.ApUserMapper;
import com.usian.user.mapper.ApUserRealNameMapper;
import com.usian.user.service.ApUserRealNameService;
import io.seata.spring.annotation.GlobalTransactional;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.Date;

@Service
public class ApUserRealNameServiceImpl extends ServiceImpl<ApUserRealNameMapper,
        ApUserRealname> implements ApUserRealNameService {

    @Autowired
    ApUserMapper apUserMapper;

    @Autowired
    ApAuthorFeign apAuthorFeign;

    @Autowired
    WmUserFeign wmUserFeign;

    public static final Short PASS_AUTH = 9;
    public static final Short FAIL_AUTH = 2;

    @Override
    public ResponseResult findPage(AuthDto dto) {
        if (dto==null || dto.getStatus()==null){
            return ResponseResult.errorResult(AppHttpCodeEnum.SERVER_ERROR);
        }
        dto.checkParam();

        Page page = new Page(dto.getPage(),dto.getSize());
        QueryWrapper<ApUserRealname> queryWrapper = new QueryWrapper<>();
        if (dto.getStatus()!=null && dto.getStatus()!=3){
            queryWrapper.lambda().eq(ApUserRealname::getStatus,dto.getStatus());
        }

        IPage result = page(page,queryWrapper);

        PageResponseResult responseResult =
                new PageResponseResult(dto.getPage(), dto.getSize(), (int) result.getTotal());

        responseResult.setData(result.getRecords());

        return responseResult;
    }

    /**
     * 用户申请成为自媒体账户审核
     * 状态 9 成功，创建wemedia wmuser  创建article apauthor
     * 状态 2 失败，返回失败原因
     * @param dto
     * @param status
     * @return
     */
    @Override
    @GlobalTransactional  //开启全局事物控制(分布式事物控制)
    public ResponseResult updateStatusById(AuthDto dto, Short status) {
        //参数校检
        if (dto==null){
            return ResponseResult.errorResult(AppHttpCodeEnum.PARAM_INVALID);
        }

        if (status!=9 && status!=2){
            return ResponseResult.errorResult(AppHttpCodeEnum.PARAM_INVALID);
        }

        ApUserRealname UserRealname = this.getById(dto.getId());

        //审核失败，更新apuserrealname表
        ApUserRealname apUserRealname = new ApUserRealname();
        apUserRealname.setId(dto.getId());
        apUserRealname.setStatus(status);
        if (dto.getMsg()!=null){
            apUserRealname.setReason(dto.getMsg());
        }
        apUserRealname.setUpdatedTime(new Date());
        this.updateById(apUserRealname);


        //审核认证通过 状态9 ，则创建自媒体和作者账号
        if (status.equals(PASS_AUTH)){
            ResponseResult result = this.createWmUserAndAuthor(dto,UserRealname.getUserId());
            if (result.getCode()!=0){
                return ResponseResult.errorResult(AppHttpCodeEnum.SERVER_ERROR);
            }

            //更新apuser表中 flag标识
            ApUser apUser = new ApUser();
            apUser.setId(UserRealname.getUserId());
            apUser.setFlag(Short.valueOf("1")); //自媒体人
            apUserMapper.updateById(apUser);
//            int a = 100/0;
        }

        return ResponseResult.okResult(AppHttpCodeEnum.SUCCESS);
    }


    //创建自媒体和作者账号
    private ResponseResult createWmUserAndAuthor(AuthDto dto,Integer userId) {
        ApUser apUser = apUserMapper.selectById(userId);
        if (apUser==null){
            return ResponseResult.errorResult(AppHttpCodeEnum.DATA_NOT_EXIST);
        }
        //根据name查询wmUser表数据是否存在
        WmUser wmUser = wmUserFeign.findByName(apUser.getName());
        if (wmUser==null){
            wmUser = new WmUser();
            //设置ApUserId
            wmUser.setApUserId(apUser.getId());
            wmUser.setCreatedTime(new Date());
            wmUser.setSalt(apUser.getSalt());
            wmUser.setName(apUser.getName());
            wmUser.setPassword(apUser.getPassword());
            wmUser.setStatus(9);
            wmUser.setPhone(apUser.getPhone());
            WmUser wmUser1 = wmUserFeign.save(wmUser);

            ApAuthor apAuthor = apAuthorFeign.findByUserId(wmUser.getApUserId());
            if (apAuthor==null){
                apAuthor = new ApAuthor();
                apAuthor.setName(wmUser.getName());
                apAuthor.setType(2);
                apAuthor.setCreatedTime(new Date());
                apAuthor.setUserId(wmUser.getApUserId());
                apAuthor.setWmUserId(wmUser1.getId());
                apAuthorFeign.saveAuthor(apAuthor);

            }
        }

        return ResponseResult.okResult(AppHttpCodeEnum.SUCCESS);

    }
}
